<template>
  <div class="workflow-instance">
    <!-- 搜索表单 -->
    <el-form
      ref="searchRef"
      :model="searchParam"
      :inline="true"
      class="search-form"
    >
      <el-form-item label="工作流名称" prop="workflowName">
        <el-input
          v-model="searchParam.param.workflowName"
          placeholder="请输入工作流名称"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="业务键" prop="businessKey">
        <el-input
          v-model="searchParam.param.businessKey"
          placeholder="请输入业务键"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="searchParam.param.status"
          placeholder="请选择状态"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="option in WORKFLOW_INSTANCE_STATUS_OPTIONS"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
        <el-button type="success" @click="handleStartInstance">
          <el-icon><Plus /></el-icon>
          启动实例
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      v-loading="loading"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="workflowName" label="工作流名称" width="200" show-overflow-tooltip />
      <el-table-column prop="businessKey" label="业务键" width="150" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ getStatusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="startUser" label="发起人" width="120" />
      <el-table-column prop="startTime" label="开始时间" width="180" />
      <el-table-column prop="endTime" label="结束时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleViewTrace(row)">
            轨迹
          </el-button>
          <el-button 
            v-if="row.status === 0" 
            type="warning" 
            size="small" 
            @click="handlePause(row)"
          >
            暂停
          </el-button>
          <el-button 
            v-if="row.status === 3" 
            type="success" 
            size="small" 
            @click="handleResume(row)"
          >
            恢复
          </el-button>
          <el-button 
            v-if="row.status === 0 || row.status === 3" 
            type="danger" 
            size="small" 
            @click="handleTerminate(row)"
          >
            终止
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="searchParam.curPage"
        v-model:page-size="searchParam.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="searchParam.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 启动实例对话框 -->
    <el-dialog
      v-model="startDialogVisible"
      title="启动工作流实例"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="startFormRef"
        :model="startForm"
        :rules="startFormRules"
        label-width="100px"
      >
        <el-form-item label="工作流" prop="workflowId">
          <el-select v-model="startForm.workflowId" placeholder="请选择工作流" style="width: 100%">
            <el-option
              v-for="workflow in workflowList"
              :key="workflow.id"
              :label="workflow.name"
              :value="workflow.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业务键" prop="businessKey">
          <el-input v-model="startForm.businessKey" placeholder="请输入业务键" />
        </el-form-item>
        <el-form-item label="流程变量" prop="variables">
          <el-input
            v-model="startForm.variablesText"
            type="textarea"
            :rows="4"
            placeholder="请输入JSON格式的流程变量，如：{&quot;key1&quot;: &quot;value1&quot;}"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="startDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleStartSubmit" :loading="startLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 轨迹回显对话框 -->
    <el-dialog
      v-model="traceDialogVisible"
      title="工作流轨迹"
      width="90%"
      :close-on-click-modal="false"
      class="trace-dialog"
    >
      <WorkflowTrace 
        v-if="traceDialogVisible"
        :instance-id="currentInstanceId"
        @close="traceDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import { Search, Refresh, Plus } from '@element-plus/icons-vue';
import { 
  getWorkflowInstanceList,
  startWorkflowInstance,
  pauseWorkflowInstance,
  resumeWorkflowInstance,
  terminateWorkflowInstance,
  getWorkflowList
} from '@/api/workflow';
import type { WorkflowInstance, Workflow } from '@/api/workflow/WorkflowModel';
import { WORKFLOW_INSTANCE_STATUS_OPTIONS } from '@/api/workflow/WorkflowModel';
import WorkflowTrace from './WorkflowTrace.vue';

// Props
const props = defineProps<{
  workflowId: number;
}>();

// Emits
const emit = defineEmits<{
  close: [];
}>();

// 响应式数据
const searchRef = ref<FormInstance>();
const startFormRef = ref<FormInstance>();

// 表格数据
const tableData = ref<WorkflowInstance[]>([]);
const loading = ref(false);

// 搜索参数
const searchParam = reactive({
  curPage: 1,
  pageSize: 10,
  total: 0,
  pages: 0,
  param: {
    workflowName: '',
    businessKey: '',
    status: undefined
  }
});

// 选中的行
const selectedKeys = ref<number[]>([]);

// 对话框
const startDialogVisible = ref(false);
const traceDialogVisible = ref(false);
const startLoading = ref(false);

// 当前实例ID
const currentInstanceId = ref<number | null>(null);

// 工作流列表
const workflowList = ref<Workflow[]>([]);

// 启动表单
const startForm = reactive({
  workflowId: props.workflowId || null,
  businessKey: '',
  variablesText: '{}'
});

// 启动表单验证规则
const startFormRules = {
  workflowId: [
    { required: true, message: '请选择工作流', trigger: 'change' }
  ],
  businessKey: [
    { required: true, message: '请输入业务键', trigger: 'blur' }
  ]
};

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger',
    3: 'info'
  };
  return typeMap[status as keyof typeof typeMap] || 'info';
};

// 获取状态标签
const getStatusLabel = (status: number) => {
  const option = WORKFLOW_INSTANCE_STATUS_OPTIONS.find(opt => opt.value === status);
  return option?.label || '未知';
};

// 获取实例列表
const loadInstanceList = async () => {
  try {
    loading.value = true;
    const params = {
      ...searchParam,
      workflowId: props.workflowId
    };
    const response = await getWorkflowInstanceList(params);
    tableData.value = response.data.records || [];
    searchParam.total = response.data.total || 0;
    searchParam.pages = response.data.pages || 0;
  } catch (error) {
    ElMessage.error('获取实例列表失败');
  } finally {
    loading.value = false;
  }
};

// 获取工作流列表
const loadWorkflowList = async () => {
  try {
    const response = await getWorkflowList({
      curPage: 1,
      pageSize: 1000,
      total: 0,
      pages: 0,
      param: {
        status: 1 // 只获取已发布的工作流
      }
    });
    workflowList.value = response.data.records || [];
  } catch (error) {
    ElMessage.error('获取工作流列表失败');
  }
};

// 搜索
const handleSearch = () => {
  searchParam.curPage = 1;
  loadInstanceList();
};

// 重置
const handleReset = () => {
  searchRef.value?.resetFields();
  searchParam.param.workflowName = '';
  searchParam.param.businessKey = '';
  searchParam.param.status = undefined;
  searchParam.curPage = 1;
  loadInstanceList();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  searchParam.pageSize = val;
  searchParam.curPage = 1;
  loadInstanceList();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  searchParam.curPage = val;
  loadInstanceList();
};

// 选择改变
const handleSelectionChange = (selection: WorkflowInstance[]) => {
  selectedKeys.value = selection.map(item => item.id);
};

// 启动实例
const handleStartInstance = () => {
  startForm.workflowId = props.workflowId || null;
  startForm.businessKey = '';
  startForm.variablesText = '{}';
  startDialogVisible.value = true;
};

// 启动提交
const handleStartSubmit = async () => {
  if (!startFormRef.value) return;
  
  try {
    await startFormRef.value.validate();
    startLoading.value = true;
    
    let variables = {};
    try {
      variables = JSON.parse(startForm.variablesText);
    } catch (error) {
      ElMessage.error('流程变量格式错误，请输入有效的JSON格式');
      return;
    }
    
    await startWorkflowInstance(startForm.workflowId!, startForm.businessKey, variables);
    ElMessage.success('启动成功');
    startDialogVisible.value = false;
    loadInstanceList();
  } catch (error) {
    ElMessage.error('启动失败');
  } finally {
    startLoading.value = false;
  }
};

// 查看轨迹
const handleViewTrace = (data: WorkflowInstance) => {
  currentInstanceId.value = data.id;
  traceDialogVisible.value = true;
};

// 暂停实例
const handlePause = async (data: WorkflowInstance) => {
  try {
    await ElMessageBox.confirm(
      `确定要暂停实例"${data.businessKey}"吗？`,
      '暂停确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await pauseWorkflowInstance(data.id);
    ElMessage.success('暂停成功');
    loadInstanceList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('暂停失败');
    }
  }
};

// 恢复实例
const handleResume = async (data: WorkflowInstance) => {
  try {
    await ElMessageBox.confirm(
      `确定要恢复实例"${data.businessKey}"吗？`,
      '恢复确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await resumeWorkflowInstance(data.id);
    ElMessage.success('恢复成功');
    loadInstanceList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('恢复失败');
    }
  }
};

// 终止实例
const handleTerminate = async (data: WorkflowInstance) => {
  try {
    await ElMessageBox.confirm(
      `确定要终止实例"${data.businessKey}"吗？终止后不可恢复！`,
      '终止确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await terminateWorkflowInstance(data.id);
    ElMessage.success('终止成功');
    loadInstanceList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('终止失败');
    }
  }
};

// 初始化
onMounted(() => {
  loadInstanceList();
  loadWorkflowList();
});
</script>

<style scoped>
.search-form {
  margin-bottom: 16px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}

:deep(.el-table .el-table__row) {
  cursor: pointer;
}

:deep(.el-table .el-table__row:hover) {
  background-color: var(--el-table-row-hover-bg-color);
}

:deep(.trace-dialog .el-dialog__body) {
  padding: 0;
  height: 80vh;
}
</style>

